package main

import (
	"bufio"
	"fmt"
	"net/http"
	"os"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"

	"dowmload/convert"
)

func main() {
	fmt.Println("hello")
	r := gin.Default()
	// cros

	crosConf := cors.DefaultConfig()
	crosConf.AllowOrigins = []string{"*"}
	r.Use(cors.New(crosConf))
	// json返回
	r.GET("/", func(ctx *gin.Context) {
		ctx.JSON(200, gin.H{"hello": "world"})
	})

	// 文件下载
	// 读取文件返回字节流
	r.GET("/download-excel", func(ctx *gin.Context) {
		file, err := os.Open("./demo.xlsx")
		if err != nil {
			ctx.JSON(200, err.Error())
			return
		}
		stat, err := file.Stat()
		if err != nil {
			fmt.Println(err)
			return
		}
		bs := make([]byte, stat.Size())
		_, err = bufio.NewReader(file).Read(bs)

		ctx.Data(http.StatusOK, "application/octet-stream", bs)
	})

	// 直接返回文件
	r.GET("/excel-file", func(ctx *gin.Context) {
		ctx.File("./demo.xlsx")
	})

	// 内存数据包装文件字节流
	r.GET("/make-file", func(ctx *gin.Context) {
		type Person struct {
			Name    string
			Age     int
			Address string
		}

		var per []Person = []Person{
			{
				"AAA",
				20,
				"aaa",
			}, {
				"BBB",
				19,
				"bbb",
			}, {
				"CCC",
				21,
				"ccc",
			},
		}

		var cop = make([]any, 0)
		for _, v := range per {
			cop = append(cop, v)
		}
		by, err := convert.ConvertToXlsx(cop, []string{"姓名", "年龄", "地址"})
		if err != nil {
			ctx.JSON(200, err.Error())
		}
		ctx.Data(http.StatusOK, "application/octet-stream", by)
	})
	r.Run(":8080")
}
